<?php
define('BR', "\n");
/**
 * @property Order_queue_mdl $orderQueue
 * @property Order_cache_mdl $orderCache
 */
class Order extends CI_Controller {
	public function __construct() {
		parent::__construct ();
		$this->load->model('Order_queue_mdl','orderQueue');
	}

	public function end(){
		$this->load->model('Order_mdl','order');

		$orderID = 1409;
		$endTime = 1473150984+100;

		$res = $this->order->end($orderID,$endTime);
		var_dump($res,$this->db->queries);
	}

    public function show(){
        var_dump('sss');
    }



	public function mongo(){
		$t1 = microtime(true);
		$this->load->model('Order_cache_mdl','orderCache');
		$id = $this->orderCache->generateOrderID();
		$t = microtime(true) - $t1;
		var_dump($id,$t);

	}

	function cache(){
// 		ini_set('mongo.native_long',1);
		$this->load->database();
		$this->load->model('Order_cache_mdl','cache');
		$list = $this->db->get('hs_order_0',10)->result_array();
// 		var_dump($list);die;
		foreach( $list as $order ){
// 			$id = $order['id'];
			$id = sprintf("1%02d%09d",0,$order['id']);
			$order['id'] = (float)$id;
			$this->cache->saveOrder($order);
		}


	}


	public function queue(){
		$time = time();
		$orderIdList = array(1,2,3,4,5,7,8,9,10);

		// 发送授权
		// 创建订单
		foreach ($orderIdList as $orderID){
			$time = time();
// 			$this->orderQueue->acess($orderID, $time);
// 			$this->orderQueue->begin($orderID, $time, 1, 40);
			$this->orderQueue->flowing($orderID, $time);
		}

// 		while( !empty($orderIdList) ){
// 			shuffle($orderIdList);
// 			$state = mt_rand(0, 2)==0 ? 'end' : 'flowing';
// 			$orderID =

// 		}

		$list = $this->orderQueue->findUnfinishOrders();
		pr($list);


// 		foreach ($list as $state){
// 			$time+=3;
// 			$this->orderQueue->put($orderID, $state, $time);
// 		}

// 		$data = $this->orderQueue->get($orderID);
// 		pr($data);
	}


	/**
	 * 模拟用户买水
	 */
	public function buy(){
		sleep(randTime());
		$orderID = substr(round(microtime(true)*1000),-7).mt_rand(100, 999);
		echo $orderID,BR;
		$this->orderQueue->acess($orderID, time());
		echo 'ACESS:',time(),BR;
		sleep(randTime());
		$this->orderQueue->begin($orderID, time(), 1, 40);
		echo 'BEGIN:',time(),BR;
		$count = mt_rand(3, 10);
		while (($count--) > 0) {
			$sleep = randTime();
			sleep( $sleep );
			$time = time();
			$this->orderQueue->flowing($orderID, $time);
			echo 'FLOWING:',time(),BR;
			if( $sleep>4 ){
				echo 'EXP:',$time,BR;
				exit($time);
			}
		}

		sleep(randTime());
		$this->orderQueue->end($orderID, time());
		echo 'END:',time(),BR;
		echo '--------------------',BR;
	}

}

function randTime(){
	return mt_rand(20, 450)/100;
}


